<?php
class ModelArticleActivity extends BaseModel {

    protected function table(){
        return "wp_posts";
    }

    protected function primary_key_name(){
        return "ID";
    }

    public function get_province_list(){
        return  $this->db->query("select * from country order by country_id")->rows;
    }
    public function get_city_list($id){
        return  $this->db->query("select * from zone where country_id={$id} order by zone_id")->rows;
    }

    public function add($data) {
        $status = 'publish';

        if(isset($data['action']) && $data['action'] == '保存草稿箱')
            $status = 'draft';

        $sql = "INSERT INTO " . $this->table() . " SET post_title = '{$data['post_title']}',post_content = '{$data['post_content']}',image = '{$data['image']}',post_status='{$status}',post_type = 'activity' ";
        $this->db->query($sql);

        $id = $this->db->getLastId();

        if($id > 0 && isset($data['post_categories'])){
            foreach ($data['post_categories'] as $taxonomy_id){
                $this->db->query("INSERT INTO wp_term_relationships SET object_id = {$id},term_taxonomy_id = '{$taxonomy_id}' ");
            }
        }


        return $id;
    }

    public function edit($id, $data) {
        $status = 'publish';

        if(isset($data['action']) && $data['action'] == '保存草稿箱')
            $status = 'draft';

        $sql = "UPDATE " . $this->table() . " SET post_title = '{$data['post_title']}',post_content = '{$data['post_content']}',image = '{$data['image']}',post_status='{$status}' WHERE {$this->primary_key_name()}={$id}";
        $this->db->query($sql);

        $this->db->query("DELETE FROM wp_term_relationships WHERE object_id={$id}");

        if(isset($data['post_categories'])){
            foreach ($data['post_categories'] as $taxonomy_id){
                $this->db->query("INSERT INTO wp_term_relationships SET object_id = {$id},term_taxonomy_id = '{$taxonomy_id}' ");
            }
        }


        return $id;
    }

    public function delete($id) {
        parent::delete($id);
        $this->db->query("DELETE FROM wp_term_relationships WHERE object_id={$id}");
        $this->db->query("DELETE FROM customer_activity_article WHERE post_id={$id}");
    }

    public function getList($data = array()) {
        $sql = "SELECT a.*  FROM " . DB_PREFIX . $this->table() . " a  WHERE a.post_status = '{$data['status']}' and a.post_type = 'activity' ";
        if (!empty($data['filter_title'])) {
            $sql .= " AND post_title LIKE '{$this->db->escape($data['filter_title'])}%'";
        }
        if (!empty($data['filter_category'])) {
            $sql .= " AND exists(SELECT 1 from  wp_term_relationships b
                    join wp_term_taxonomy c on b.term_taxonomy_id = c.term_taxonomy_id
                    join wp_terms d on c.term_id = d.term_id
                    where b.object_id = a.ID and  c.term_taxonomy_id = {$data['filter_category']}) ";
        }

        $sort_data = array(
            $this->primary_key_name()
        );

        if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql .= " ORDER BY " . $data['sort'];
        } else {
            $sql .= " ORDER BY " . $sort_data[0];
        }

        if (isset($data['order']) && ($data['order'] == 'ASC')) {
            $sql .= " ASC";
        } else {
            $sql .= " DESC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if ($data['start'] < 0) {
                $data['start'] = 0;
            }

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }

            $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }

        $query = $this->db->query($sql);

        $ret = $query->rows;

        foreach ($ret as &$item){
            $item['category_names'] = $this->db->query("SELECT GROUP_CONCAT(distinct d. NAME SEPARATOR ',') name 
                                                            from wp_posts a join wp_term_relationships b on a.Id = b.object_id
                                                            join wp_term_taxonomy c on b.term_taxonomy_id = c.term_taxonomy_id
                                                            join wp_terms d on c.term_id = d.term_id
                                                            where a.ID = {$item[$this->primary_key_name()]}")->row['name'];

            if(isset($item['post_modified'])){
                $item['modify_date'] = $item['post_modified'];
            }
            else{
                $item['modify_date'] = $item['post_date'];
            }

        }
        return $ret;
    }

    public function getCount($data = array()) {
        $sql = "SELECT count(*) as total  FROM " . DB_PREFIX . $this->table() . " a  WHERE a.post_status = '{$data['status']}' and a.post_type = 'activity' ";
        if (!empty($data['filter_title'])) {
            $sql .= " AND post_title LIKE '{$this->db->escape($data['filter_title'])}%'";
        }
        if (!empty($data['filter_category'])) {
            $sql .= " AND exists(SELECT 1 from  wp_term_relationships b
                    join wp_term_taxonomy c on b.term_taxonomy_id = c.term_taxonomy_id
                    join wp_terms d on c.term_id = d.term_id
                    where b.object_id = a.ID and  c.term_taxonomy_id = {$data['filter_category']}) ";
        }
        $query = $this->db->query($sql );

        return $query->row['total'];
    }

    public function getItem($id) {
        $item = parent::getItem($id);

        $sql = "SELECT
                    c.term_taxonomy_id
                FROM
                    wp_posts a
                JOIN wp_term_relationships b ON a.ID = b.object_id
                JOIN wp_term_taxonomy c ON b.term_taxonomy_id = c.term_taxonomy_id
                JOIN wp_terms d ON c.term_id = d.term_id
                WHERE
                    a.ID = {$id}
                AND c.taxonomy = 'category'";

        $post_categories = array();
        foreach ($this->db->query($sql)->rows as $row){
            $post_categories[] = $row['term_taxonomy_id'];
        }

        $item['post_categories'] = $post_categories;

        return $item;

    }


    function send_to_grades($post_ids, $grade_ids, $operator_id ,$sendTime) {

        if (!isset($sendTime) || utf8_strlen($sendTime) == 0)
            $sendTime = 'now()';
        else
            $sendTime = "'{$sendTime}'";
        $ids_str = join(",",$post_ids);

        $grades_ary = array();
        foreach ($grade_ids as $grade){
            if ($grade == 1){
                $grades_ary[] = "一年级";
            }
            if ($grade == 2){
                $grades_ary[] = "二年级";
            }
            if ($grade == 3){
                $grades_ary[] = "三年级";
            }
            if ($grade == 4){
                $grades_ary[] = "四年级";
            }
            if ($grade == 5){
                $grades_ary[] = "五年级";
            }
            if ($grade == 6){
                $grades_ary[] = "六年级";
            }
            if ($grade == 7){
                $grades_ary[] = "初一";
            }
            if ($grade == 8){
                $grades_ary[] = "初二";
            }
            if ($grade == 9){
                $grades_ary[] = "初三";
            }
            if ($grade == 10){
                $grades_ary[] = "高一";
            }
            if ($grade == 11){
                $grades_ary[] = "高二";
            }
            if ($grade == 12){
                $grades_ary[] = "高三";
            }
        }

        $push_detail = join(",",$grades_ary);
        $this->db->query("update wp_posts set last_avail_time={$sendTime},send_time= now(),post_modified=post_modified,post_modified_gmt=post_modified_gmt,push_grades='{$push_detail}' where ID in ({$ids_str}) ");

        $sql = "insert into customer_activity_article(customer_id,post_id,operator_id,avail_time) ";
        $first = true;
        foreach ( $post_ids as $post_id ) {
            foreach ( $grade_ids as $grade_id ) {
                if($first){
                    $sql .= "select customer_id,{$post_id},{$operator_id},{$sendTime} from customer_child
						where CEIL(TIMESTAMPDIFF(Month,grade,CURRENT_TIMESTAMP)  / 12) = {$grade_id}";
                    $first = false;
                }
                else{
                    $sql .= " union all select customer_id,{$post_id},{$operator_id},{$sendTime} from customer_child
						where CEIL(TIMESTAMPDIFF(Month,grade,CURRENT_TIMESTAMP)  / 12) = {$grade_id}";
                }

            }

        }


        return $this->db->query($sql)->rows;
    }

    function send_to_cities($post_ids, $cities_ids, $operator_id ,$sendTime){
        if (!isset($sendTime) || utf8_strlen($sendTime) == 0)
            $sendTime = 'now()';
        else
            $sendTime = "'{$sendTime}'";
        $ids_str = join(",",$post_ids);


        $ids_city = join(",",$cities_ids);

        $push_detail =  $this->db->query("select GROUP_CONCAT(name) as names from zone where zone_id in ({$ids_city}) ")->row['names'];


        $this->db->query("update wp_posts set last_avail_time={$sendTime},send_time= now(),post_modified=post_modified,post_modified_gmt=post_modified_gmt,push_cities='{$push_detail}' where ID in ({$ids_str}) ");

        $sql = "insert into customer_activity_article(customer_id,post_id,operator_id,avail_time) ";
        $first = true;

        if(count($post_ids)){
            $sql .= "select distinct * from(";
        }

        foreach ( $post_ids as $post_id ) {
            if($first){
                $sql .= "select customer_id,{$post_id} as post_id,{$operator_id} as operator_id,{$sendTime} as sentTime from customer
						where zone_id in ({$ids_city})";
                $first = false;
            }
            else{
                $sql .= "union all select customer_id,{$post_id},{$operator_id},{$sendTime} from customer
						where zone_id in ({$ids_city})";
            }

        }

        if(count($post_ids)){
            $sql .= ") a";
        }


        return $this->db->query($sql)->rows;
    }

    function publish($post_ids) {


        foreach ( $post_ids as $post_id ) {
            $sql = "UPDATE " . $this->table() . " SET publish_time=now(),post_status='publish' WHERE {$this->primary_key_name()}={$post_id}";
            $this->db->query($sql);

        }


    }


}